package com.share.three.netty.delimiter;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/*
 * 采用分隔符的方式解决拆包粘包的问题：  DelimiterBasedFrameDecoder
 */
public class Server {

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup);
			b.channel(NioServerSocketChannel.class);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.option(ChannelOption.SO_BACKLOG, 1024);
			b.option(ChannelOption.SO_RCVBUF, 32*1024);
			b.option(ChannelOption.SO_SNDBUF, 32*1024);
			b.childHandler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ByteBuf delimiter = Unpooled.copiedBuffer("$".getBytes());
					//设置分隔符
					ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
					//设置字符串形式的解码--->读可以，写还要bytebuf
					ch.pipeline().addLast(new StringDecoder());
					ch.pipeline().addLast(new ServerHandler());

				}

			});
			
			ChannelFuture f = b.bind(12345).sync();
			System.out.println("server 启动 。。。");

			f.channel().closeFuture().sync();
			

		} catch (Exception e) {
			System.out.println(e);
		} finally {
			 bossGroup.shutdownGracefully();
			 workerGroup.shutdownGracefully();
		}

	}

}
